package com.ys.controller.api.eKnowAi;

import com.alibaba.fastjson.JSONObject;
import com.ys.config.MyConfig;
import com.ys.entity.eKnowAi.EKnowKnowledgeBase;
import com.ys.entity.eKnowAi.EKnowKnowledgeList;
import com.ys.enume.eKnowAi.EknowCodeEnum;
import com.ys.util.baidu.ApiHttpClientUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/inter/knowledgeHitTest")
public class ApiInterKnowledgeHitTestController {
	private static final Logger logger = LoggerFactory.getLogger(ApiInterKnowledgeHitTestController.class);


	private static String URLAPI = MyConfig.getUrlApi1_5();

	@Autowired
	private ApiHttpClientUtils apiHttpUtils;

	/**
	 * 查询知识库列表
	 */
	//@RequiresPermissions("eKnowKnowledgeList:view")
	@RequestMapping("/getKnowledgeBase")
	@ResponseBody
	public JSONObject getKnowledgeBase(HttpServletRequest request, HttpServletResponse response){
		JSONObject result = new JSONObject();
		try {
			List<EKnowKnowledgeBase> eKnowKnowledgeBase = new EKnowKnowledgeBase().setOrderby("A.Sort ASC").queryList();
			result.put("eKnowKnowledgeBase",eKnowKnowledgeBase);
			result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("逸知道查询知识库列表出错：",e.getMessage(),e);
		}
		return result;
	}

	/**
	 * 根据问题、关键词获取知识库
	 */
	@PostMapping("/getKnowledgeByInput")
	@ResponseBody
	public JSONObject getKnowledgeByInput(HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
		JSONObject result = new JSONObject();
		try {
			String baseIds = params.get("baseIds").toString();
			String question = params.get("question").toString();
			int size = Integer.parseInt(params.get("size").toString());
			float score = Float.parseFloat(params.get("score").toString())/100;

			List<EKnowKnowledgeBase> eKnowKnowledgeBase = new EKnowKnowledgeBase()
					.where("A.Id IN ("+baseIds+")")
					.queryList();

			if(eKnowKnowledgeBase!=null && eKnowKnowledgeBase.size()>0) {

				String getKnowledgeUrl = URLAPI + "/api/outer/baiDuEKnowAi/searchKnowledgeList";
				Map<String, Object> sendParamsBygetKnowledge = new HashMap<>();
				List<String> informationList = new ArrayList<>();
				informationList.add(question);//问题
				List<String> indexNameList = new ArrayList<>();
				for (EKnowKnowledgeBase item : eKnowKnowledgeBase) {
					indexNameList.add(item.getESIndexName());
				}

				sendParamsBygetKnowledge.put("information", informationList);//问题
				sendParamsBygetKnowledge.put("size", size);//向量数据库调用个数
				sendParamsBygetKnowledge.put("score", score);//置信度
				sendParamsBygetKnowledge.put("indexNameList", indexNameList);//知识库索引名称
				//向量数据库新增向量数据接口
				JSONObject embeddingBack = apiHttpUtils.sendHttpPost(sendParamsBygetKnowledge, getKnowledgeUrl);
				if (embeddingBack.get("shardIdList") != null) {
					logger.info("向量数据库新增向量数据接口返回参数：" + embeddingBack);
					//int embeddingTokens = Integer.parseInt(embeddingBack.get("totalTokens").toString());//向量化花费的tokens数

					String shardId = null;
					String shardIdOrderBy = null;
					List<Map<String, Object>> shardIdList = (List<Map<String, Object>>) embeddingBack.get("shardIdList");
					if (shardIdList.size() > 0) {
						for (Map<String, Object> item : shardIdList) {
							if (shardId == null || shardId.equals("")) {
								shardId = "'" + item.get("id").toString() + "'";
								shardIdOrderBy = item.get("id").toString();
							} else {
								shardId = shardId + ",'" + item.get("id").toString() + "'";
								shardIdOrderBy = shardIdOrderBy + "," + item.get("id").toString() ;
							}
						}
						List<Map<String,Object>> getSceneKnowledgeList = new EKnowKnowledgeList()
								.addField("B.KnowledgeBaseName AS knowledgeBaseName")
								.addLeftJoin("kjecp_eknow.dbo.EKnow_KnowledgeBase B ON B.Id = A.BaseId")
								.where("A.ESId IN (" + shardId + ")")
								.setOrderby("charindex(RTRIM(CAST(A.ESId AS VARCHAR(50))),'"+shardIdOrderBy+"')")
								.queryMap();
						result.put("getSceneKnowledgeList", getSceneKnowledgeList);
						result.put("shardIdList", shardIdList);
					}
				}
			}
			result.put("code", EknowCodeEnum.ApiRetuenCode.SUCCESS);
		}catch (Exception e) {
			result.put("code", EknowCodeEnum.ApiRetuenCode.FAIL);
			logger.error("逸知道根据问题、关键词获取知识库出错：",e.getMessage(),e);
		}
		return result;
	}


}